<script setup lang="ts">
import { ref, watch, toRaw } from "vue"
import { downloadTaskProcessFileApi, searchTaskFileApi } from "@@/apis/train"
import { useRoute } from "vue-router"
const route = useRoute()
interface Props {
  id?: string
  visible: boolean
  connectedNodes?: string[]
}

const props = defineProps<Props>()
const emit = defineEmits(["close-dialog"])
const downDataList = ref<any>([])

const drawerVisible = ref(false)
const exportType = ref("TXT")

const textMap = "导出评估结果"
// 下载
const handleDownload = (downDataList) => {
  const process_file_ids = toRaw(downDataList)
  downloadTaskProcessFileApi(route.query.id, {
    process_file_ids: process_file_ids,
    format: "txt"
  }).then((res) => {
    const blob = new Blob([res.data])
    const contentPosition = res.headers["content-disposition"]
    if (contentPosition) {
      const match = contentPosition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      const fileName = match[1].replace(/['"]/g, "")
      if ("download" in document.createElement("a")) {
        const elink = document.createElement("a")
        elink.download = fileName
        elink.style.display = "none"
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      }
    } else {
      ElMessage.error("下载失败")
    }
  })
}
const handleSreach = (id: string, data: any) => {
  searchTaskFileApi(id, data).then(({ data }) => {
    data.rows.forEach((item) => {
      downDataList.value.push(item.file_id)
    })
  })
}
// 监听visible prop的变化
watch(
  () => props.visible,
  (newVal) => {
    drawerVisible.value = newVal
  }
)

// 监听连接节点变化
watch(
  () => props.connectedNodes,
  (newVal) => {
    let processedNodeIds = []
    let ids = []
    if (newVal) {
      // 处理每个节点ID，去掉下划线及其后面的数字，并去重
      processedNodeIds = newVal
      processedNodeIds.forEach((id) => {
        ids.push(Number(id))
      })
    } else {
      ids = []
    }
    handleSreach(route.query.id, ids)
  },
  { immediate: true, deep: true } // 添加immediate选项，确保首次加载时也会执行
)

const closeDialog = () => {
  emit("close-dialog")
}

const handleCloseTip = (done: () => void) => {
  emit("close-dialog")
  done()
}

const downloadResult = () => {
  // TODO: 实现下载逻辑
}

defineExpose({
  drawerVisible
})
</script>

<template>
  <el-drawer
    v-model="drawerVisible"
    direction="rtl"
    size="600px"
    @close-auto-focus="closeDialog"
    @close="closeDialog"
    :before-close="handleCloseTip"
  >
    <template #header>
      <h4>{{ textMap }}</h4>
    </template>

    <div class="drawer-content">
      <!-- 参数配置 -->
      <div class="section">
        <div class="section-title">参数配置</div>
        <div class="export-type">
          <div class="label">导出类型</div>
          <el-radio-group v-model="exportType">
            <el-radio label="TXT">TXT</el-radio>
            <el-radio label="Word">Word</el-radio>
            <el-radio label="PDF">PDF</el-radio>
          </el-radio-group>
        </div>
      </div>
      <!-- 运行结果 -->
      <div class="section">
        <div class="section-title">运行结果</div>
        <div class="result-area">
          <!-- 这里可以添加运行结果的展示 -->
        </div>
      </div>

      <!-- 下载按钮 -->
      <div class="download-section">
        <el-button type="primary" @click="handleDownload(downDataList)">下载运行结果</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<style scoped>
.drawer-content {
  padding: 20px;
}

.section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}

.export-type {
  display: flex;
  align-items: center;
  gap: 20px;
}

.label {
  min-width: 70px;
}

.download-section {
  margin-top: 40px;
  text-align: center;
}

.result-area {
  min-height: 200px;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 20px;
}

.connected-nodes {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.node-tag {
  margin-right: 8px;
}
</style>
